import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useSupplierStore = defineStore('supplier', () => {
  const STORAGE_KEY = 'erppos_suppliers'
  const suppliers = ref([])

  const initialize = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    if (cached) { suppliers.value = JSON.parse(cached); return }
    suppliers.value = [
      { id: 'S001', name: '华东服饰', contact: '张三', phone: '13800000011', address: '上海市黄浦区', settle: '月结' },
      { id: 'S002', name: '星辉制衣', contact: '李四', phone: '13900000022', address: '广州市海珠区', settle: '现结' },
    ]
    persist()
  }

  const persist = () => { localStorage.setItem(STORAGE_KEY, JSON.stringify(suppliers.value)) }

  const add = (data) => { const item = { id: 'S' + Date.now(), ...data }; suppliers.value.unshift(item); persist(); return item }
  const update = (id, data) => { const i = suppliers.value.findIndex(x=>x.id===id); if(i>-1){ suppliers.value[i] = { ...suppliers.value[i], ...data }; persist(); return suppliers.value[i] } return null }
  const remove = (id) => { const i = suppliers.value.findIndex(x=>x.id===id); if(i>-1){ suppliers.value.splice(i,1); persist(); return true } return false }
  const total = computed(() => suppliers.value.length)

  return { suppliers, initialize, add, update, remove, total }
})


